package com.zimi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.mapper.SysOrgExtendMapper;
import com.zimi.mapper.SysOrgRoleEmpowerMapper;
import com.zimi.mapper.SysRoleMapper;
import com.zimi.mapper.SysRolePrivilegeMapper;
import com.zimi.model.SysOrgExtend;
import com.zimi.model.SysOrgRoleEmpower;
import com.zimi.model.SysRolePrivilege;
import com.zimi.model.SysUser;
import com.zimi.util.CommonUtil;
import com.zimi.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色功能授权表 Service
 *
 * @author lnintr
 * @since 2019-05-26
 */
@Service
public class SysRolePrivilegeService {
    @Autowired
    private SysRolePrivilegeMapper sysRolePrivilegeMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysOrgExtendMapper sysOrgExtendMapper;

    @Autowired
    private SysOrgRoleEmpowerMapper sysOrgRoleEmpowerMapper;

    @Autowired
    private CommonUtil commonUtil;

    /*
     * 取得组织和角色信息
     * */
    public Object getOrglistByRole(SysOrgExtend sysOrgExtend) {
        // 1)权限控制
        Map map = commonUtil.getOrgList();
        List<SysOrgExtend> list = sysOrgExtendMapper.getMineOgnList(map);

        if (list != null && list.size() > 0) {

            // 2)取得指定用户的选择机构信息
            List<SysOrgRoleEmpower> listRole = sysOrgRoleEmpowerMapper.selectList(new QueryWrapper<SysOrgRoleEmpower>().lambda().eq(SysOrgRoleEmpower::getRoleId, sysOrgExtend.getRoleId()));
            Map<Integer, SysOrgRoleEmpower> roleMap = null;

            if (listRole != null && listRole.size() > 0) {
                roleMap = new HashMap<>();
                for (SysOrgRoleEmpower sore : listRole) {
                    roleMap.put(sore.getOrgId(), sore);
                }
            }

            // 3)设置选中标志的值
            for (SysOrgExtend soe : list) {
                if (roleMap != null) {
                    SysOrgRoleEmpower sysOrgRoleEmpower = (SysOrgRoleEmpower) roleMap.get(soe.getOrgId());

                    if (sysOrgRoleEmpower != null) {
                        soe.setId(sysOrgRoleEmpower.getId());
                        soe.setUpdateTime(sysOrgRoleEmpower.getUpdateTime());

                        if (sysOrgRoleEmpower.getSoreState() == 1) {
                            soe.setChoiceFlag(true);
                        } else {
                            soe.setChoiceFlag(false);
                        }
                    } else {
                        soe.setChoiceFlag(false);
                        soe.setId(0);
                    }
                } else {
                    soe.setChoiceFlag(false);
                    soe.setId(0);
                }
            }

            // 4)取得并合并机构分类
            List<SysOrgExtend> orgCateList = sysOrgExtendMapper.getMineOgnCateList((List<Integer>) map.get("ognIdList"));

            if (orgCateList != null && orgCateList.size() > 0) {
                list.addAll(orgCateList);
            }
        }

        return list;
    }


    /*
     * 取得权限和角色信息
     * */
    public Object getFunctionlistByRole(SysOrgExtend sysOrgExtend) {
        // 1)取得所有功能

        List<SysOrgExtend> list = sysOrgExtendMapper.selectFunctionList(sysOrgExtend);

        if (list != null && list.size() > 0) {
            // 2)取得所有功能信息
            List<SysRolePrivilege> listFunction = sysRolePrivilegeMapper.selectList(new QueryWrapper<SysRolePrivilege>().lambda().eq(SysRolePrivilege::getRoleId, sysOrgExtend.getRoleId()));
            Map<Integer, SysRolePrivilege> roleMap = null;

            if (listFunction != null && listFunction.size() > 0) {
                roleMap = new HashMap<>();
                for (SysRolePrivilege srpl : listFunction) {
                    roleMap.put(srpl.getFunctionId(), srpl);
                }
            }

            // 设置选中标志的值
            for (SysOrgExtend soe : list) {
                if (roleMap != null) {
                    SysRolePrivilege sysRolePrivilege = (SysRolePrivilege) roleMap.get(soe.getFunctionId());

                    if (sysRolePrivilege != null) {
                        soe.setId(sysRolePrivilege.getId());
                        soe.setUpdateTime(sysRolePrivilege.getUpdateTime());

                        if (sysRolePrivilege.getPrivilegeState() == 1) {
                            soe.setChoiceFlag(true);
                        } else {
                            soe.setChoiceFlag(false);
                        }
                    } else {
                        soe.setChoiceFlag(false);
                        soe.setId(0);
                    }
                } else {
                    soe.setChoiceFlag(false);
                    soe.setId(0);
                }
            }
        }

        return list;
    }


    @Transactional
    public void saveOrgRole(SysOrgExtend sysOrgExtend, int flag) {
        List<Integer> idList = new ArrayList<>();
        if (sysOrgExtend != null) {
            SysUser user = UserUtil.getUser();
            Date updateTime = new Date();

            // 1）对要修改的对象加行锁
            SysOrgRoleEmpower result = sysOrgRoleEmpowerMapper.selectOne(new QueryWrapper<SysOrgRoleEmpower>().lambda().eq(SysOrgRoleEmpower::getRoleId, sysOrgExtend.getRoleId()).eq(SysOrgRoleEmpower::getOrgId, sysOrgExtend.getOrgId()).last("for update"));
            if (result != null) {
                if (sysOrgExtend.getUpdateTime() != null) {
                    if (result.getUpdateTime() != null && result.getUpdateTime().getTime() != sysOrgExtend.getUpdateTime().getTime()) {
                        throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
                    }
                }

                result.setUpdateUser(user.getId());
                result.setUpdateTime(updateTime);
                result.setSoreState(flag);
                result.updateById();
            } else {
                result = new SysOrgRoleEmpower();

                result.setCreateUser(user.getId());
                result.setCreateTime(updateTime);
                result.setSoreState(flag);
                result.setRoleId(sysOrgExtend.getRoleId());
                result.setOrgId(sysOrgExtend.getOrgId());

                result.insert();
            }
        }
    }

    @Transactional
    public void saveFunctionOrg(List<SysOrgExtend> sysOrgExtends, int flag) {
        List<Integer> idList = new ArrayList<>();
        if (sysOrgExtends != null && sysOrgExtends.size() > 0) {

            int roleId = sysOrgExtends.get(0).getRoleId();
            SysRolePrivilege tmpOrgExtend = null;

            for (SysOrgExtend soe : sysOrgExtends) {
                idList.add(soe.getFunctionId());
            }

            // 1）对要修改的对象加行锁
            List<SysRolePrivilege> results = sysRolePrivilegeMapper.selectList(new QueryWrapper<SysRolePrivilege>().lambda().eq(SysRolePrivilege::getRoleId, roleId).in(SysRolePrivilege::getFunctionId, idList).last("for update"));

            Map<Integer, SysRolePrivilege> resMap = null;

            if (results != null && results.size() > 0) {
                resMap = new HashMap<>();

                for (SysRolePrivilege srp : results) {
                    resMap.put(srp.getFunctionId(), srp);
                }
            }

            SysUser user = UserUtil.getUser();
            Date updateTime = new Date();

            // 2)所属权限创建或修改
            for (SysOrgExtend soe : sysOrgExtends) {
                if (resMap != null) {
                    tmpOrgExtend = resMap.get(soe.getFunctionId());

                    // 3）判断该数据已经被改过没有
                    if (tmpOrgExtend != null) {
                        if (tmpOrgExtend.getUpdateTime() != null) {
                            if (soe.getUpdateTime() != null && soe.getUpdateTime().getTime() != tmpOrgExtend.getUpdateTime().getTime()) {
                                throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
                            }
                        }

                        tmpOrgExtend.setUpdateUser(user.getId());
                        tmpOrgExtend.setUpdateTime(updateTime);
                        tmpOrgExtend.setPrivilegeState(flag);
                        tmpOrgExtend.updateById();
                    } else {
                        tmpOrgExtend = new SysRolePrivilege();

                        tmpOrgExtend.setCreateUser(user.getId());
                        tmpOrgExtend.setCreateTime(updateTime);
                        tmpOrgExtend.setPrivilegeState(flag);
                        tmpOrgExtend.setRoleId(roleId);
                        tmpOrgExtend.setFunctionId(soe.getFunctionId());

                        tmpOrgExtend.insert();
                    }
                } else {
                    tmpOrgExtend = new SysRolePrivilege();

                    tmpOrgExtend.setCreateUser(user.getId());
                    tmpOrgExtend.setCreateTime(updateTime);
                    tmpOrgExtend.setPrivilegeState(flag);
                    tmpOrgExtend.setRoleId(roleId);
                    tmpOrgExtend.setFunctionId(soe.getFunctionId());

                    tmpOrgExtend.insert();
                }
            }
        }
    }
}
